// pages/facePay/facePay.js
import {
  postRequest,
  getRequest,
  postParamsRequest
} from '../../api/request';
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    themeColor: app.globalData.themeColor,
    subColor: app.globalData.subColor,
    btnColor: app.globalData.btnColor,
    memberId: app.myInfo.memberId,
    globalData: {},
    price: "",
    remark: "",
    rechargeDiscountRule: [], //会员充值
    userInfo: {}, //用户信息
    submitClose: true, //是否不允许提交订单
    payType: 1, //支付方式
    isPay: false,
    submitLock: true,
    KeyboardKeys: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, '.'],

    // price: '', // 支付金额
    keyHidden: false,
    surePay:false, //是否支付成功

  },
  backIndex(){
    wx.switchTab({
      url: '../index/index'
    })
  },
  // 隐藏键盘
  handleHiddenKey() {
    this.setData({
      keyHidden: true
    })
  },
  // 显示键盘
  handleShowKey() {
    this.setData({
      keyHidden: false
    })
  },
  // 键盘输入
  handleKey(e) {
    const that = this
    const {
      key
    } = e.currentTarget.dataset
    const {
      price
    } = this.data
    // 删除金额
    if (key === 'X') {
      if (price !== '') {
        const money = price.slice(0, price.length - 1)
        that.setData({
          price: money
        })
      }
    } else {
      // 添加金额
      const money = price + key
      console.log(/^(\d+\.?\d{0,2})$/.test(money), money, 'money')
      if (/^(\d+\.?\d{0,2})$/.test(money)) {
        that.setData({
          price: money
        })
      }
    }
  },
  // 支付
  handlePay() {
    const {
      price
    } = this.data
    if (price === '') return
    wx.showLoading({
      title: "提交中...",
      icon: "none",
      mask: true,
    });
    let self = this;
    let parame = {
      memberId: app.myInfo.memberId,
      price: this.data.price,
      remark: "备注"
    }
    postParamsRequest("/api/createFacePayCardOrder", parame).then((res) => {
      console.log('res', res.data.data)
      //判断是微信支付还是储值
      console.log('this.data.payType', this.data.payType)
      if (this.data.payType == 1) {
        postParamsRequest("/api/order/payFacePayOrder", {
          orderId: res.data.data,
        }).then((res2) => {
          console.log('微信支付的接口res2',res2)
          let data = res2.data.data;
          wx.requestPayment({
            'timeStamp': data.timeStamp,
            'nonceStr': data.nonceStr,
            'package': data.package,
            'signType': data.signType,
            'paySign': data.paySign,
            'success': function (res3) {
              console.log('微信支付的接口res3',res3)
              wx.hideLoading();
              self.setData({
                isPay: true,
                surePay:true
              })
              //支付成功跳转订单详情页
              // wx.redirectTo({
              //   url: '../orderDetail/orderDetail?orderId='
              // })
            },
            'fail': function (err) {
              console.log('res3res3res3',err)
              wx.hideLoading();
              self.setData({
                submitLock: false,
              })
              wx.showToast({
                title: '支付失败',
                icon:'error'
              })
              //支付成功跳转订单详情页
              // wx.redirectTo({
              //   url: '../orderDetail/orderDetail?orderId=' + res.data.data.orderId + "&orderType=" + sureOrderType
              // })
            }
          })

        }).catch((err) => {
          wx.hideLoading();
          self.setData({
            submitLock: false
          })
        });
      } else if (this.data.payType == 4) {
        if (res.data.message != "成功") {
          wx.showToast({
            title: '储值支付失败',
            icon:'error'
          })
        } else {
          wx.showToast({
            title: '储值支付成功',
          })
          // wx.redirectTo({
          //   url: '../orderDetail/orderDetail?orderId=' + res.data.data.orderId + "&orderType=" + sureOrderType
          // })
        }
        wx.hideLoading();
        self.setData({
          submitLock: false
        })
      } else if (this.data.payType == 8) {
        if (res.data.message != "成功") {
          wx.showToast({
            title: '支付失败',
            icon:'error'
          })
        } else {
          wx.showToast({
            title: '支付成功',
          })
          // wx.redirectTo({
          //   url: '../orderDetail/orderDetail?orderId=' + res.data.data.orderId + "&orderType=" + sureOrderType
          // })
        }
        wx.hideLoading();
        self.setData({
          submitLock: false
        })
      }

    })
    console.log(Number(price), '付款')
  },
  // 创建订单
  createFacePay() {
    if (this.data.price < 0) {
      return
    }
    wx.showLoading({
      title: "提交中...",
      icon: "none",
      mask: true,
    });
    let self = this;
    let parame = {
      memberId: app.myInfo.memberId,
      price: this.data.price,
      remark: "备注"
    }
    postParamsRequest("/api/createFacePayCardOrder", parame).then((res) => {
      console.log('res', res.data.data)
      //判断是微信支付还是储值
      console.log('this.data.payType', this.data.payType)
      if (this.data.payType == 1) {
        postParamsRequest("/api/order/payFacePayOrder", {
          orderId: res.data.data,
        }).then((res2) => {

          let data = res2.data.data;
          wx.requestPayment({
            'timeStamp': data.timeStamp,
            'nonceStr': data.nonceStr,
            'package': data.package,
            'signType': data.signType,
            'paySign': data.paySign,
            'success': function (res3) {

              wx.hideLoading();
              self.setData({
                isPay: true,
              })
              //支付成功跳转订单详情页
              // wx.redirectTo({
              //   url: '../orderDetail/orderDetail?orderId='
              // })
            },
            'fail': function (err) {

              wx.hideLoading();
              self.setData({
                submitLock: false,
              })
              wx.showToast({
                title: '支付失败',
                icon:'error'
              })
              //支付成功跳转订单详情页
              // wx.redirectTo({
              //   url: '../orderDetail/orderDetail?orderId=' + res.data.data.orderId + "&orderType=" + sureOrderType
              // })
            }
          })

        }).catch((err) => {
          wx.hideLoading();
          self.setData({
            submitLock: false
          })
        });
      } else if (this.data.payType == 4) {
        if (res.data.message != "成功") {
          wx.showToast({
            title: '支付失败',
            icon:'error'
          })
        } else {
          wx.showToast({
            title: '储值支付成功',
          })
          // wx.redirectTo({
          //   url: '../orderDetail/orderDetail?orderId=' + res.data.data.orderId + "&orderType=" + sureOrderType
          // })
        }
        wx.hideLoading();
        self.setData({
          submitLock: false
        })
      } else if (this.data.payType == 8) {
        if (res.data.message != "成功") {
          wx.showToast({
            title: '支付失败',
          })
        } else {
          wx.showToast({
            title: '支付成功',
          })
          // wx.redirectTo({
          //   url: '../orderDetail/orderDetail?orderId=' + res.data.data.orderId + "&orderType=" + sureOrderType
          // })
        }
        wx.hideLoading();
        self.setData({
          submitLock: false
        })
      }

    })
  },

  //支付方式改变
  onPayTypeChange(e) {
    this.setData({
      payType: e.currentTarget.dataset.type,
    });
    //储值支付时,如果余额不足不能提交订单
    if (this.data.payType == 4) {
      if (this.data.userInfo.cardRemaining * 1 < this.data.payAmt) {
        this.setData({
          submitClose: true,
        })
      }
    } else {
      this.setData({
        submitClose: false,
      })
    }
    if (this.data.payDiscountType == 1) {
      this.getPreOrder(false, false);
    }
  },
  //获取个人信息
  getUserBaseInfo() {
    let that = this;
    return new Promise(function (resolve, reject) {
      getRequest("/api/vip/getUserBaseInfo", {
        memberId: app.myInfo.memberId
      }).then((res) => {

        if (res.data.data != null) {
          wx.hideLoading()
          wx.setStorageSync('userInfo', res.data.data);
          that.setData({
            userInfo: res.data.data,
          })
        }
        resolve(res);
      }).catch((err) => {
        wx.hideLoading();
        reject(err);
      });
    });
  },
  //获取会员配置
  getMemberConfig() {
    let that = this;
    return new Promise(function (resolve, reject) {
      getRequest("/api/vip/member/config", {}).then((res) => {

        if (res.data.data != null) {
          let rule = res.data.data.rechargeDiscountRule == '' ? [] : JSON.parse(res.data.data.rechargeDiscountRule);
          wx.hideLoading()
          that.setData({
            rechargeDiscountRule: rule,
            payDiscountType: res.data.data.payDiscountType
          });
        }
        resolve(res);
      }).catch((err) => {
        reject(err);
      });
    })
  },

  //获取店铺风格
  getShopInfo() {
    let that = this;
    getRequest("/api/shop/getShopInfo", {
      beid: app.beid
    }).then(res => {
      console.log(res, 'res')
      app.globalConfig = res.data.data;

      that.setData({
        globalData: res.data.data,

      })
      wx.setStorageSync('shopInfo', res.data.data);
      wx.setStorageSync('paymentPriority', res.data.data.paymentPriority)
      // todo 
      wx.hideLoading()
    }).catch((err) => {
      console.log(err)
    });
  },
  //金额改变时
  changePrice(e) {
    this.setData({
      price: e.detail.value
    })
  },
  changeRemark(e) {
    this.setData({
      remark: e.detail.value
    })
  },
  //前往充值页面
  toStoredValuePage() {
    wx.navigateTo({
      url: '../storedValue/storedValue',
    })
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //如果没有token,则需要重新登录获取个人信息等，避免缺少id导致数据无法获取
    wx.showLoading({
      title: "加载中...",
      icon: "none"
    });
    if (app.token == "" || app.token == undefined) {    
      app.initLogin().then(res => {
        this.getShopInfo();
      }).catch(err => {})
    } else {
      this.getShopInfo();
      this.getMemberConfig();
      this.getUserBaseInfo()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})